package designpattern

import (
	"encoding/xml"
	"fmt"
	"os"
)

type Product struct {
	XMLName     xml.Name `xml:"product"`
	Id          int      `xml:"id"`
	Name        string   `xml:"name"`
	Weight      float64  `xml:"weight"`
	High        float64  `xml:"high"`
	Description string   `xml:"description"`
}

func (source *Product) Clone() *Product {
	return &Product{Id: source.Id, Name: source.Name, Weight: source.Weight, High: source.High, Description: source.Description}
}

func NewProduct() (*Product, error) {
	println("Create object from xml file...")
	file, err := os.Open("../config/Product.xml")
	defer file.Close()
	if err != nil {
		return nil, err
	}

	fileinfo, err := file.Stat()
	if err != nil {
		return nil, err
	}

	bytes := make([]byte, fileinfo.Size())
	bytesread, err := file.Read(bytes)
	if bytesread == 0 {
		return nil, fmt.Errorf("Nothing to read")
	}

	if err != nil {
		return nil, err
	}
	var product *Product
	xml.Unmarshal(bytes, &product)

	return product, nil
}
